define(['jquery', 'bootstrap', 'backend', 'table', 'form','upload'], function ($, undefined, Backend, Table, Form,Upload) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'material/index',
                    add_url: 'material/add',
                    edit_url: '',
                    del_url: 'material/del',
                }
            });
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        {field: 'state', checkbox: true},
                        {field: 'thumb',width:"45px" ,title: __('封面'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'title', title: __('标题'),align:'left'},
                        {field: 'created_at',width:"145px", title: __('更新时间'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {field: 'operate',width:"125px",align:'right', title: __('Operate'), table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                    name: 'detail',
                                    text: '',
                                    title:'修改',
                                    icon: 'fa fa-pencil',
                                    classname: 'btn btn-info btn-xs btn-detail',
                                    url: 'material/edit?ids={ids}'
                                }],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        item:function(){
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'material/index',
                    add_url: 'material/add',
                    edit_url: '',
                    del_url: 'material/del',
                }
            });
            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                showColumns:false,
                showToggle:false,
                columns: [
                    [
                        {field: 'thumb',width:"45px" ,title: __('封面'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'title', title: __('标题'),align:'left'},
                        {field: 'created_at',width:"145px", title: __('更新时间'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {field: 'operate',width:"125px",align:'right', title: __('Operate'), table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                    name: 'detail',
                                    text: '确定',
                                    title:'确定',
                                    icon: 'fa fa-plus',
                                    classname: 'btn btn-primary btn-xs btn-confirm',
                                    url:'ajax/getMaterialItem?ids={ids}',
                                }],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
            $("body").on("click",".btn-confirm",function(){
                var _this = $(this);
                if(_this.hasClass('disabled')){
                    return false;
                }
                _this.addClass('disabled');
               var indexLay = Layer.load(1)
                $.post(_this.attr('href'),{},function(ret){
                    _this.removeClass('disabled');
                    Layer.close(indexLay)
                    if(ret.code == 0){
                        Toastr.error(ret.msg);
                        return ;
                    }
                    $(".content-material", window.parent.document).html(ret.data.html);
                    Fast.api.close({})

                })
                return false;
            })
        },
        add: function () {
            
            Controller.api._init();
        },
        edit: function () {
            Controller.api._init();
        },
        api:{
            save:function(isload){
                if(isload){

                }
            },
            _init:function(){

                var sort = [];
                let data = oldData || [];
                var aid = $(".active").data('aid');
                var ikey = $(".material_item").length;
                data[aid] = Controller.api.formDataForArr();
                sort[aid] = 0;
                
                // 新建图文
                $("body").on("click",".newMaterial",function(){
                    var aid = $(".active").data('aid');
                    $(".active").removeClass("active");
                    //var ikey = Math.floor(Math.random()*100000000);
                    var itemHtml = $("#_material_itme_html").html();
                    itemHtml = itemHtml.replace(/{_index}/g,ikey)
                    $(".material-body").append(itemHtml);
                    if($(".material_item").length >= 8){
                        $(".material-footer").hide()
                    }
                    data[aid] = Controller.api.formDataForArr();
                    $("#p-image").html('');
                    $(".reset-btn").click();
                    Controller.api._intFormData();
                    sort[aid] = ikey;
                    ikey++;
                })
                // 点击图文
                $("body").on("click",".material_item",function(){
                    // 先把当前的表单值存储
                    var oldAid = $(".active").data('aid');
                    data[oldAid] = Controller.api.formDataForArr();
                    // 切换新的图文
                    $(".active").removeClass("active");
                    $(this).addClass('active');
                    $(".reset-btn").click();
                    Controller.api._intFormData();
                    $("#p-image").html('');
                    var aid = $(this).data("aid");
                    var formDatas = data[aid];
                    Controller.api.setFormData(formDatas);
                    
                })
                // 失去焦点
                $("body").on("input propertychange","#c-title",function(){
                    $(".active").find("._title").text($(this).val());
                })
                // 上传成功
                $("#faupload-image").data("upload-success", function(rest){
                    if($(".active").hasClass("item-1")){
                        $(".active").find("._thumb").css("background-image","url("+rest.url+")");
                    }else{
                        $(".active").find("._thumb").attr('src',rest.url);
                    }
                    $("#thumb_media_id").val(rest.media_id)
                });
                $("body").on('click',"#_submit",function(){
                    var oldAid = $(".active").data('aid');
                    data[oldAid] = Controller.api.formDataForArr();
                    var layerIndex = Layer.load(1)
                    var datas = Controller.api.getItemData(data);
                    $.post("",{row:datas},function(ret){
                        Layer.close(layerIndex)
                        if(ret.code == 0){
                            if(ret.data.index != undefined){
                                $(".active").removeClass("active");
                                $("#appmsg-item-"+ret.data.index).addClass('active')
                                Controller.api.setFormData(data[ret.data.index]);
                                $("form[role=form]").submit();
                            }
                        }else{
                            Toastr.success(ret.msg);
                            setTimeout(function(){
                                location.href=ret.url
                            },2000)
                        }
                    })
                })
                // 删除图文
                $("body").on('click',".remove-item",function(){
                    $(this).parent().prev().click();
                    $(this).parent().remove();
                    
                })
                Form.api.bindevent($("form[role=form]"));
            },
            formDataForArr(){
                return $("form[role=form]").serializeArray();
                var datas = [];
                $.each(formData, function(i, field){
                    datas[field.name] = field.value;
                });
                return datas;
            },
            setFormData(formDatas){
                for(var i in formDatas){
                    if($("[name='"+formDatas[i].name+"']").length > 0){
                        $("[name='"+formDatas[i].name+"']").val(formDatas[i].value);
                        // 图片
                    }
                    // checkbox选项
                    if(formDatas[i].name == 'need_open_comment' || formDatas[i].name == 'only_fans_can_comment'){ // 简介
                        if(formDatas[i].value == 1){
                            $("[name='"+formDatas[i].name+"']").prop("checked",true)
                        }else{
                            $("[name='"+formDatas[i].name+"']").prop("checked",false)
                        }
                    }
                    if(formDatas[i].name == 'content'){
                        $('.editor').summernote('code',formDatas[i].value);
                    }  
                }
            },
            _intFormData:function(){  //初始化表单值
                var formDatas = $("form[role=form]").serializeArray();
                for(var i in formDatas){
                    if($("[name='"+formDatas[i].name+"']").length > 0){
                        $("[name='"+formDatas[i].name+"']").val('');
                    }
                    // checkbox选项
                    if(formDatas[i].name == 'need_open_comment'){ // 简介
                        $("[name='"+formDatas[i].name+"']").prop("checked",false)
                    } 
                    if(formDatas[i].name == 'only_fans_can_comment'){ // 简介
                        $("[name='"+formDatas[i].name+"']").prop("checked",false);
                    } 
                }
                $('.editor').summernote('code',"");
            },
            getItemData:function(data){
                var basr = [];
                $.each($(".material_item"),function(i,item){
                    var aid = $(item).data('aid')
                    if(data[aid] != undefined){
                        basr[aid] = data[aid];
                    }
                })
                return basr;
            }
        }
        
    };
    return Controller;
});
